from mongoengine import  ValidationError
from rest_framework_mongoengine import serializers
from rest_framework_mongoengine import fields
from .exception_handler import *
from spit.models import Spit
from django.utils import timezone
import pytz

#
class MyDateTimeField(fields.serializers.DateTimeField):
      # mongo的publishtime
    def enforce_timezone(self, value):
        # value是０时区时间，但无时区属性
        value = value.replace(tzinfo=pytz.timezone('UTC'))
        return super().enforce_timezone(value=value)

class SpitSerializer(serializers.DocumentSerializer):

    publishtime = MyDateTimeField()
    class Meta:
        model = Spit
        fields = "__all__"


    def create(self, validated_data):

        # spit = super().create(validated_data)
        parent = validated_data.get('parent')
        try:
            user = self.context["request"].user
        except:
            user = None

        #    判断是否是评论别人
        if parent:
            # 评论别人必须登陆
            if user and user.is_authenticated:

                spit = super().create(validated_data)


                spit.userid = str(user.id)
                spit.nickname = user.nickname if user.nickname else user.username
                spit.avatar = user.avatar
                spit.save()
                spit.parent.comment += 1
                spit.parent.save()

                return spit
            else:
                raise ValidationError('未登录')
        else:
            spit = super().create(validated_data)
            return spit